{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-1-a825bb8ff0e5>:18: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From <ipython-input-1-a825bb8ff0e5>:97: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See @{tf.nn.softmax_cross_entropy_with_logits_v2}.\n",
      "\n",
      "step 100, entropy loss: 1.029303, l2_loss: 12641.266602, total loss: 1.914192\n",
      "0.7\n",
      "step 200, entropy loss: 0.614523, l2_loss: 12639.710938, total loss: 1.499303\n",
      "0.79\n",
      "step 300, entropy loss: 0.546208, l2_loss: 12638.112305, total loss: 1.430876\n",
      "0.84\n",
      "step 400, entropy loss: 0.249612, l2_loss: 12636.522461, total loss: 1.134169\n",
      "0.9\n",
      "step 500, entropy loss: 0.262506, l2_loss: 12634.845703, total loss: 1.146945\n",
      "0.95\n",
      "step 600, entropy loss: 0.233908, l2_loss: 12633.198242, total loss: 1.118232\n",
      "0.92\n",
      "step 700, entropy loss: 0.282835, l2_loss: 12631.543945, total loss: 1.167043\n",
      "0.93\n",
      "step 800, entropy loss: 0.294601, l2_loss: 12629.888672, total loss: 1.178693\n",
      "0.94\n",
      "step 900, entropy loss: 0.132811, l2_loss: 12628.225586, total loss: 1.016786\n",
      "0.97\n",
      "step 1000, entropy loss: 0.159828, l2_loss: 12626.496094, total loss: 1.043682\n",
      "0.97\n",
      "0.9374\n",
      "step 1100, entropy loss: 0.278236, l2_loss: 12624.809570, total loss: 1.161973\n",
      "0.91\n",
      "step 1200, entropy loss: 0.199795, l2_loss: 12623.150391, total loss: 1.083415\n",
      "0.93\n",
      "step 1300, entropy loss: 0.122910, l2_loss: 12621.454102, total loss: 1.006412\n",
      "0.97\n",
      "step 1400, entropy loss: 0.246280, l2_loss: 12619.758789, total loss: 1.129663\n",
      "0.9\n",
      "step 1500, entropy loss: 0.154700, l2_loss: 12618.037109, total loss: 1.037962\n",
      "0.95\n",
      "step 1600, entropy loss: 0.119545, l2_loss: 12616.359375, total loss: 1.002691\n",
      "0.95\n",
      "step 1700, entropy loss: 0.142172, l2_loss: 12614.648438, total loss: 1.025197\n",
      "0.96\n",
      "step 1800, entropy loss: 0.150663, l2_loss: 12612.970703, total loss: 1.033571\n",
      "0.91\n",
      "step 1900, entropy loss: 0.147004, l2_loss: 12611.259766, total loss: 1.029792\n",
      "0.99\n",
      "step 2000, entropy loss: 0.078440, l2_loss: 12609.570312, total loss: 0.961110\n",
      "0.97\n",
      "0.9566\n",
      "step 2100, entropy loss: 0.163503, l2_loss: 12607.880859, total loss: 1.046055\n",
      "0.94\n",
      "step 2200, entropy loss: 0.241739, l2_loss: 12606.188477, total loss: 1.124172\n",
      "0.94\n",
      "step 2300, entropy loss: 0.162574, l2_loss: 12604.502930, total loss: 1.044889\n",
      "0.96\n",
      "step 2400, entropy loss: 0.048191, l2_loss: 12602.787109, total loss: 0.930386\n",
      "0.98\n",
      "step 2500, entropy loss: 0.098950, l2_loss: 12601.068359, total loss: 0.981025\n",
      "0.98\n",
      "step 2600, entropy loss: 0.164575, l2_loss: 12599.317383, total loss: 1.046527\n",
      "0.95\n",
      "step 2700, entropy loss: 0.114561, l2_loss: 12597.589844, total loss: 0.996392\n",
      "0.99\n",
      "step 2800, entropy loss: 0.100862, l2_loss: 12595.887695, total loss: 0.982574\n",
      "0.98\n",
      "step 2900, entropy loss: 0.062331, l2_loss: 12594.182617, total loss: 0.943924\n",
      "1.0\n",
      "step 3000, entropy loss: 0.204753, l2_loss: 12592.464844, total loss: 1.086226\n",
      "0.97\n",
      "0.9645\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "#构造一个reshape函数，重构输入图片数据大小\n",
    "with tf.name_scope('reshape'):\n",
    "    x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "#第一个卷积层\n",
    "with tf.name_scope('conv1'):\n",
    "    shape = [5, 5, 1, 32]                                                         #先用32通道5*5卷积核\n",
    "    W_conv1 = tf.Variable(tf.truncated_normal(shape, stddev=0.1),                 #权重的初始化方法采用截断的正太分布方法，一开始的方差设置为0.1\n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])    \n",
    "    shape = [32]\n",
    "    b_conv1 = tf.Variable(tf.constant(0.1, shape=shape))                          #偏置量的初始化方法采用固定值初始化，参数为0.1\n",
    "    l_conv1 = tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv1                                #padding参数设置为SAME\n",
    "    h_conv1 = tf.nn.relu(l_conv1)\n",
    "\n",
    "with tf.name_scope('pool1'):\n",
    "    h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')                    #padding参数设置为Valid\n",
    "\n",
    "\n",
    "with tf.name_scope('conv2'):\n",
    "    W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1),        #第二层的卷积核数量为64个\n",
    "                        \n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_conv2 = tf.Variable(tf.constant(0.1, shape=[64]))\n",
    "    l_conv2 = tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv2                                #padding参数设置为SAME\n",
    "    h_conv2 = tf.nn.relu(l_conv2)\n",
    "\n",
    "\n",
    "with tf.name_scope('pool2'):\n",
    "    h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')\n",
    "\n",
    "\n",
    "with tf.name_scope('fc1'):\n",
    "    W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1),\n",
    "                      \n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))\n",
    "\n",
    "    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n",
    "    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "\n",
    "with tf.name_scope('dropout'):\n",
    "    keep_prob = tf.placeholder(tf.float32)\n",
    "    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "\n",
    "with tf.name_scope('fc2'):\n",
    "    W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1),\n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))\n",
    "\n",
    "    y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n",
    "\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection('WEIGHTS')] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss                                          #初始化正则因子为7e-5\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "\n",
    "for step in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    lr = 0.01\n",
    "    _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "    if (step+1) % 100 == 0:\n",
    "        print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "    if (step+1) % 1000 == 0:\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 调整卷积核大小"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将5*5卷积核变为4*4卷积核，而通道数不改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n",
      "step 100, entropy loss: 1.172320, l2_loss: 25242.560547, total loss: 2.939299\n",
      "0.7\n",
      "step 200, entropy loss: 0.827551, l2_loss: 25239.560547, total loss: 2.594320\n",
      "0.73\n",
      "step 300, entropy loss: 0.488565, l2_loss: 25236.380859, total loss: 2.255112\n",
      "0.87\n",
      "step 400, entropy loss: 0.398262, l2_loss: 25233.156250, total loss: 2.164583\n",
      "0.87\n",
      "step 500, entropy loss: 0.332912, l2_loss: 25229.837891, total loss: 2.099001\n",
      "0.86\n",
      "step 600, entropy loss: 0.398372, l2_loss: 25226.480469, total loss: 2.164226\n",
      "0.88\n",
      "step 700, entropy loss: 0.263070, l2_loss: 25223.113281, total loss: 2.028688\n",
      "0.88\n",
      "step 800, entropy loss: 0.270334, l2_loss: 25219.714844, total loss: 2.035714\n",
      "0.95\n",
      "step 900, entropy loss: 0.369047, l2_loss: 25216.328125, total loss: 2.134190\n",
      "0.92\n",
      "step 1000, entropy loss: 0.204748, l2_loss: 25212.873047, total loss: 1.969649\n",
      "0.92\n",
      "0.9267\n",
      "step 1100, entropy loss: 0.299587, l2_loss: 25209.470703, total loss: 2.064250\n",
      "0.93\n",
      "step 1200, entropy loss: 0.263400, l2_loss: 25206.052734, total loss: 2.027824\n",
      "0.96\n",
      "step 1300, entropy loss: 0.208207, l2_loss: 25202.628906, total loss: 1.972391\n",
      "0.93\n",
      "step 1400, entropy loss: 0.282486, l2_loss: 25199.175781, total loss: 2.046428\n",
      "0.9\n",
      "step 1500, entropy loss: 0.117429, l2_loss: 25195.750000, total loss: 1.881131\n",
      "0.93\n",
      "step 1600, entropy loss: 0.161336, l2_loss: 25192.310547, total loss: 1.924798\n",
      "0.97\n",
      "step 1700, entropy loss: 0.056998, l2_loss: 25188.869141, total loss: 1.820218\n",
      "0.96\n",
      "step 1800, entropy loss: 0.128445, l2_loss: 25185.460938, total loss: 1.891427\n",
      "0.96\n",
      "step 1900, entropy loss: 0.159304, l2_loss: 25182.011719, total loss: 1.922045\n",
      "0.95\n",
      "step 2000, entropy loss: 0.298240, l2_loss: 25178.574219, total loss: 2.060740\n",
      "0.88\n",
      "0.9528\n",
      "step 2100, entropy loss: 0.131900, l2_loss: 25175.144531, total loss: 1.894160\n",
      "0.94\n",
      "step 2200, entropy loss: 0.144621, l2_loss: 25171.671875, total loss: 1.906638\n",
      "0.96\n",
      "step 2300, entropy loss: 0.115477, l2_loss: 25168.214844, total loss: 1.877252\n",
      "0.97\n",
      "step 2400, entropy loss: 0.069481, l2_loss: 25164.794922, total loss: 1.831017\n",
      "0.98\n",
      "step 2500, entropy loss: 0.186175, l2_loss: 25161.335938, total loss: 1.947469\n",
      "0.98\n",
      "step 2600, entropy loss: 0.053377, l2_loss: 25157.878906, total loss: 1.814428\n",
      "0.98\n",
      "step 2700, entropy loss: 0.171351, l2_loss: 25154.404297, total loss: 1.932159\n",
      "0.95\n",
      "step 2800, entropy loss: 0.092350, l2_loss: 25150.937500, total loss: 1.852916\n",
      "0.97\n",
      "step 2900, entropy loss: 0.150463, l2_loss: 25147.484375, total loss: 1.910787\n",
      "0.95\n",
      "step 3000, entropy loss: 0.048300, l2_loss: 25144.044922, total loss: 1.808383\n",
      "0.97\n",
      "0.9617\n"
     ]
    }
   ],
   "source": [
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "#构造一个reshape函数，重构输入图片数据大小\n",
    "with tf.name_scope('reshape'):\n",
    "    x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "#第一个卷积层\n",
    "with tf.name_scope('conv1'):\n",
    "    shape = [4, 4, 1, 32]  \n",
    "    W_conv1 = tf.Variable(tf.truncated_normal(shape, stddev=0.1),\n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    shape = [32]\n",
    "    b_conv1 = tf.Variable(tf.constant(0.1, shape=shape))\n",
    "    l_conv1 = tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv1\n",
    "    h_conv1 = tf.nn.relu(l_conv1)\n",
    "\n",
    "with tf.name_scope('pool1'):\n",
    "    h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')\n",
    "\n",
    "\n",
    "with tf.name_scope('conv2'):\n",
    "    W_conv2 = tf.Variable(tf.truncated_normal([4, 4, 32, 64], stddev=0.1),\n",
    "                        \n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_conv2 = tf.Variable(tf.constant(0.1, shape=[64]))\n",
    "    l_conv2 = tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv2\n",
    "    h_conv2 = tf.nn.relu(l_conv2)\n",
    "\n",
    "\n",
    "with tf.name_scope('pool2'):\n",
    "    h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')\n",
    "\n",
    "\n",
    "with tf.name_scope('fc1'):\n",
    "    W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1),\n",
    "                      \n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))\n",
    "\n",
    "    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n",
    "    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "\n",
    "with tf.name_scope('dropout'):\n",
    "    keep_prob = tf.placeholder(tf.float32)\n",
    "    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "\n",
    "with tf.name_scope('fc2'):\n",
    "    W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1),\n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))\n",
    "\n",
    "    y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n",
    "\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection('WEIGHTS')] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "\n",
    "for step in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    lr = 0.01\n",
    "    _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "    if (step+1) % 100 == 0:\n",
    "        print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "    if (step+1) % 1000 == 0:\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将卷积核大小调小之后，准确率变低了，原因可能是由于每一次卷积计算后携带的信息减少"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "增大卷积核大小，变为6*6卷积核"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 0.786500, l2_loss: 50745.128906, total loss: 4.338659\n",
      "0.77\n",
      "step 200, entropy loss: 0.430121, l2_loss: 50738.117188, total loss: 3.981790\n",
      "0.83\n",
      "step 300, entropy loss: 0.544590, l2_loss: 50731.117188, total loss: 4.095768\n",
      "0.84\n",
      "step 400, entropy loss: 0.254161, l2_loss: 50724.125000, total loss: 3.804850\n",
      "0.96\n",
      "step 500, entropy loss: 0.303605, l2_loss: 50717.078125, total loss: 3.853800\n",
      "0.89\n",
      "step 600, entropy loss: 0.399024, l2_loss: 50710.062500, total loss: 3.948728\n",
      "0.94\n",
      "step 700, entropy loss: 0.263707, l2_loss: 50703.000000, total loss: 3.812917\n",
      "0.95\n",
      "step 800, entropy loss: 0.232686, l2_loss: 50695.945312, total loss: 3.781402\n",
      "0.92\n",
      "step 900, entropy loss: 0.162647, l2_loss: 50688.921875, total loss: 3.710871\n",
      "0.95\n",
      "step 1000, entropy loss: 0.198880, l2_loss: 50681.906250, total loss: 3.746613\n",
      "0.93\n",
      "0.9387\n",
      "step 1100, entropy loss: 0.173385, l2_loss: 50674.859375, total loss: 3.720625\n",
      "0.9\n",
      "step 1200, entropy loss: 0.373714, l2_loss: 50667.804688, total loss: 3.920461\n",
      "0.93\n",
      "step 1300, entropy loss: 0.097457, l2_loss: 50660.800781, total loss: 3.643713\n",
      "0.96\n",
      "step 1400, entropy loss: 0.134942, l2_loss: 50653.773438, total loss: 3.680706\n",
      "0.95\n",
      "step 1500, entropy loss: 0.286866, l2_loss: 50646.738281, total loss: 3.832138\n",
      "0.92\n",
      "step 1600, entropy loss: 0.280539, l2_loss: 50639.699219, total loss: 3.825318\n",
      "0.96\n",
      "step 1700, entropy loss: 0.169283, l2_loss: 50632.656250, total loss: 3.713569\n",
      "0.95\n",
      "step 1800, entropy loss: 0.172537, l2_loss: 50625.632812, total loss: 3.716331\n",
      "0.94\n",
      "step 1900, entropy loss: 0.069149, l2_loss: 50618.558594, total loss: 3.612448\n",
      "0.97\n",
      "step 2000, entropy loss: 0.245105, l2_loss: 50611.523438, total loss: 3.787912\n",
      "0.91\n",
      "0.9576\n",
      "step 2100, entropy loss: 0.183802, l2_loss: 50604.503906, total loss: 3.726118\n",
      "0.98\n",
      "step 2200, entropy loss: 0.057766, l2_loss: 50597.468750, total loss: 3.599589\n",
      "1.0\n",
      "step 2300, entropy loss: 0.084191, l2_loss: 50590.437500, total loss: 3.625522\n",
      "0.97\n",
      "step 2400, entropy loss: 0.055416, l2_loss: 50583.375000, total loss: 3.596253\n",
      "0.99\n",
      "step 2500, entropy loss: 0.091204, l2_loss: 50576.347656, total loss: 3.631548\n",
      "0.95\n",
      "step 2600, entropy loss: 0.130970, l2_loss: 50569.347656, total loss: 3.670825\n",
      "0.95\n",
      "step 2700, entropy loss: 0.187557, l2_loss: 50562.312500, total loss: 3.726919\n",
      "0.96\n",
      "step 2800, entropy loss: 0.045959, l2_loss: 50555.296875, total loss: 3.584830\n",
      "0.99\n",
      "step 2900, entropy loss: 0.127953, l2_loss: 50548.273438, total loss: 3.666332\n",
      "0.97\n",
      "step 3000, entropy loss: 0.079004, l2_loss: 50541.246094, total loss: 3.616891\n",
      "0.97\n",
      "0.9666\n"
     ]
    }
   ],
   "source": [
    "\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "#构造一个reshape函数，重构输入图片数据大小\n",
    "with tf.name_scope('reshape'):\n",
    "    x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "#第一个卷积层\n",
    "with tf.name_scope('conv1'):\n",
    "    shape = [6, 6, 1, 32]  #先用32通道5*5卷积核\n",
    "    W_conv1 = tf.Variable(tf.truncated_normal(shape, stddev=0.1),\n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    shape = [32]\n",
    "    b_conv1 = tf.Variable(tf.constant(0.1, shape=shape))\n",
    "    l_conv1 = tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv1\n",
    "    h_conv1 = tf.nn.relu(l_conv1)\n",
    "\n",
    "with tf.name_scope('pool1'):\n",
    "    h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')\n",
    "\n",
    "\n",
    "with tf.name_scope('conv2'):\n",
    "    W_conv2 = tf.Variable(tf.truncated_normal([6,6 , 32, 64], stddev=0.1),\n",
    "                        \n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_conv2 = tf.Variable(tf.constant(0.1, shape=[64]))\n",
    "    l_conv2 = tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv2\n",
    "    h_conv2 = tf.nn.relu(l_conv2)\n",
    "\n",
    "\n",
    "with tf.name_scope('pool2'):\n",
    "    h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')\n",
    "\n",
    "\n",
    "with tf.name_scope('fc1'):\n",
    "    W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1),\n",
    "                      \n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))\n",
    "\n",
    "    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n",
    "    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "\n",
    "with tf.name_scope('dropout'):\n",
    "    keep_prob = tf.placeholder(tf.float32)\n",
    "    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "\n",
    "with tf.name_scope('fc2'):\n",
    "    W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1),\n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))\n",
    "\n",
    "    y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n",
    "\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection('WEIGHTS')] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "\n",
    "for step in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    lr = 0.01\n",
    "    _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "    if (step+1) % 100 == 0:\n",
    "        print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "    if (step+1) % 1000 == 0:\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "结果比5*5卷积核好了一点。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
